package com.jeecms.cms.action.front;

import com.jeecms.cms.entity.main.Content;
import com.jeecms.cms.entity.main.ContentAttachment;
import com.jeecms.cms.manager.main.ContentMng;
import com.jeecms.common.web.ResponseUtils;
import com.jeecms.core.entity.CmsSite;
import com.jeecms.core.entity.CmsUser;
import com.jeecms.core.web.WebErrors;
import com.jeecms.core.web.util.CmsUtils;
import com.jeecms.core.web.util.FrontUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@Controller
public class DownloadDocAct {
    private static final Logger log = LoggerFactory.getLogger(DownloadDocAct.class);


    @RequestMapping(value = "/downloadDoc*.jspx", method = RequestMethod.GET)
    public String downloadDoc(Integer contentId, HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        JSONObject json = new JSONObject();

        CmsUser user = CmsUtils.getUser(request);
        CmsSite site = CmsUtils.getSite(request);

        if (user == null){
            // 需要登录才能下载
            return FrontUtils.showLogin(request, model, site);
        }
        if(contentId==null){
            return FrontUtils.showMessage(request, model,
                    "comment.contentNotFound");
        }
        Content content = contentMng.findById(contentId);
        if (content == null) {
            return FrontUtils.showMessage(request, model,
                    "comment.contentNotFound");
        }
        //财富值够才允许下载，否则不允许下载
        if (content.getDownNeed() > 0) {
            log.info("");
            return FrontUtils.showMessage(request, model, "comment.closed");
        }

        BufferedInputStream bis=null;
        BufferedOutputStream bos=null;
        try {
            List<ContentAttachment> docList = content.getAttachments();
            if(docList != null && docList.size()>0){
                ContentAttachment ca = docList.get(0);
                String attachPath = ca.getPath(); //存储文件路径+名称  原格式的
                String fileName = ca.getFilename(); //原版格式的文件名
                //文件存放路径
                String saveDirectory = request.getServletContext().getRealPath("/");
                long fileLength = new File(saveDirectory + attachPath).length();
                response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
                response.setHeader("Content-Length", String.valueOf(fileLength));
                bis = new BufferedInputStream(new FileInputStream(saveDirectory + attachPath));
                bos = new BufferedOutputStream(response.getOutputStream());
                byte[] buff = new byte[2048];
                int bytesRead;
                while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                    bos.write(buff, 0, bytesRead);
                }
                bis.close();
                bos.close();
            }else{
                ResponseUtils.renderJson(response, WebErrors.create(request).getMessage("error.hasNotFundDoc"));
            }
        }catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }



    @Autowired
    private ContentMng contentMng;
}
